﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Itfort.Net;

namespace Caifu.Spiders
{
	public class CommonSipder
	{
		public string Pattern { get; set; }
		public string FundCodeGroupName { get; set; }
		public string ReportDateGroupName { get; set; }
		public string UnitNetValueGroupName { get; set; }
		public string AccumulatedNetValueGroupName { get; set; }

		/// <summary>
		/// 忽略中源码中的日期，直接使用传入的日期作为净值日期。
		/// （这种情况是由于在源码中没有日期信息）
		/// </summary>
		public bool IgnoreReportDate { get; set; }

		/// <summary>
		/// 开启统一净值日期
		/// </summary>
		public bool EnableUnifiedReportDate { get; set; }

		/// <summary>
		/// 统一的净值日期匹配模式
		/// </summary>
		public string UnifiedReportDatePattern { get; set; }

		public CommonSipder()
		{
			FundCodeGroupName = "code";
			ReportDateGroupName = "date";
			UnitNetValueGroupName = "unv";
			AccumulatedNetValueGroupName = "anv";
		}

		public IList<NetValueItem> Crawl(string url, string encoding, DateTime date)
		{
			List<NetValueItem> netValues = new List<NetValueItem>();

			var html = HttpClient.GetHtml(url, encoding);

			if (this.EnableUnifiedReportDate)
			{
				var unifiedReportDate = this.CrawlUnifiedReportDate(html);
				if (unifiedReportDate != date)
				{
					return new List<NetValueItem>();
				}
			}

			var pattern = Pattern;
			var matchs = Regex.Matches(html, pattern);

			if (matchs.Count == 0)
			{
				// 报告问题
			}


			foreach (Match match in matchs)
			{
				NetValueItem netValue = new NetValueItem();

				try
				{
					if (!this.IgnoreReportDate && !this.EnableUnifiedReportDate)
					{
						var tdate = DateTime.Parse(match.Groups[ReportDateGroupName].Value);
						// 目标与期望不符
						if (tdate != date) continue;
					}

					netValue.ReportDate = date;
					var fundCode = match.Groups[FundCodeGroupName].Value;
					var unv = Decimal.Parse(match.Groups[UnitNetValueGroupName].Value);
					var anv = Decimal.Parse(match.Groups[AccumulatedNetValueGroupName].Value);

					netValue.FundCode = fundCode;
					netValue.UnitNetValue = unv;
					netValue.AccumulatedNetValue = anv;

					netValues.Add(netValue);
				}
				catch (Exception ex)
				{
					// 报告错误
					Trace.WriteLine(ex.Message + Environment.NewLine
						+ ex.Source + Environment.NewLine
						+ ex.StackTrace);
				}
			}

			return netValues;
		}

		DateTime CrawlUnifiedReportDate(string source)
		{
			var datePattern = UnifiedReportDatePattern;
			var dateMatchs = Regex.Matches(source, datePattern);

			if (dateMatchs.Count == 0)
			{
				// 报告问题
			}
			var dateString = dateMatchs[0].Groups["date"].Value;
			DateTime date;

			if (dateString.Contains("-") || dateString.Contains("/"))
			{
				dateString = dateString.Replace("/", "-");
				if (dateString.Length == 10)
				{

				}
				else if (dateString.Length == 8)
				{
					dateString = "20" + dateString;
				}
				else if (dateString.Length == 6)
				{

					dateString = DateTime.Today.Year + "-" + dateString;
				}
				else
				{
					throw new Exception("不能识别日期字符串" + dateString);
				}
			}
			else
			{
				if (dateString.Length == 8)
				{
					dateString = dateString.Substring(0, 4) + "-" + dateString.Substring(4, 2) + "-" + dateString.Substring(6, 2);
				}
				else if (dateString.Length == 6)
				{
					dateString = "20" + dateString.Substring(0, 2) + "-" + dateString.Substring(2, 2) + "-" + dateString.Substring(4, 2);
				}
				else if (dateString.Length == 4)
				{

					dateString = DateTime.Today.Year + dateString.Substring(0, 2) + "-" + dateString.Substring(2, 2);
				}
				else
				{
					throw new Exception("不能识别日期字符串" + dateString);
				}
			}

			return DateTime.Parse(dateString);
		}
	}
}
